/* eslint-disable global-require */
/* eslint-disable import/no-extraneous-dependencies */
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 分类css
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 压缩js
const TerserWebpackPlugin = require('terser-webpack-plugin');
// 压缩css
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
// 清理输入目录
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// 将第三方模块添加到html中 并且自动将配置中的模块添加到externals属性中让webpack忽略打包
const HtmlWebpackExternalsPulgin = require('html-webpack-externals-plugin');

const tsImportPluginFactory = require('ts-import-plugin');

module.exports = {
  mode: 'development',
  entry: {
    bundle: './src/index.tsx',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash:8].js',
  },
  devtool: 'source-map',
  devServer: {
    hot: true,
    contentBase: path.resolve(__dirname, 'dist'),
    port: '8888',
    compress: true,
    progress: true,
    open: false,
    historyApiFallback: {
      index: './index.html',
    },
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '~': path.resolve(__dirname, 'node_modules'),
    },
    extensions: ['.ts', '.tsx', '.js', '.json', 'scss', 'css'],
  },
  optimization: {
    minimizer: [
      // 压缩css支持es6语法
      new TerserWebpackPlugin({
        parallel: true,
        cache: true,
      }),
      // 压缩css
      new OptimizeCssAssetsWebpackPlugin({
        assetNameRegExp: /\.css$/g,
        // eslint-disable-next-line global-require
        cssProcessor: require('cssnano'),
      }),
    ],
  },
  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
        use: [
          {
            loader: 'eslint-loader',
            // options: {
            //     fix: true,
            // },
          },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              getCustomTransformers: () => ({
                before: [
                  tsImportPluginFactory({
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    // style: 'css',
                  }),
                ],
              }),
              compilerOptions: {
                module: 'es2015',
              },
            },
          },
        ],
      },
      {
        test: /\.css$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          'css-loader',
        ],
      },
      {
        test: /\.scss$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /node_modules/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
            options: { importLoaders: 0 }
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [require('autoprefixer')],
            },
          },
          {
            loader: 'px2rem-loader',
            options: {
              remUnit: 100,
              remPrecesion: 8,
            },
          },
          'sass-loader',
        ],
      },
      {
        test: /\.(jpg|jpeg|png|bmp|gif|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024,
              // 将图片存放在单独的文件夹中
              outputPath: 'images', // 指定输出的路径
              publicPath: '/images', // 指定构建后写入html中的路径
            },
          },
        ],
      },
      {
        test: /\.(woff|ttf|eot|svg|otf)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024,
              outputPath: 'fonts', // 指定输出的路径
              publicPath: '/fonts', // 指定构建后写入html中的路径
            },
          },
        ],
      },
    ],
  },
  plugins: [
    // 热更新插件
    new webpack.HotModuleReplacementPlugin(),
    // webpack配置ProvidePlugin后，在使用时将不再需要import和require进行引入，直接使用即可
    new webpack.ProvidePlugin({
      _: 'lodash',
    }),
    // IgnorePlugin用于忽略某些特定的模块，让 webpack 不把这些指定的模块打包进去
    new webpack.IgnorePlugin(/^\.\/locale/, /moment$/),
    // 抽离css到单独的文件中
    new MiniCssExtractPlugin({
      // filename: '[name].[contenthash].css',
      // chunkFilename: '[name].[contenthash].css',
      // 将打包后的css单独存放在styles文件夹中
      filename: 'styles/[name].[hash:8].css',
      chunkFilename: 'styles/[name].[hash:8].css',
    }),
    new HtmlWebpackExternalsPulgin({
      externals: [
        {
          module: 'moment',
          entry:
            'https://cdn.bootcdn.net/ajax/libs/moment.js/2.26.0/moment.min.js',
          global: 'moment',
        },
      ],
    }),
    new HtmlWebpackPlugin({
      title: '珠峰课堂',
      template: './public/index.html',
      filename: 'index.html',
      inject: true,
      hash: true,
      favicon: './favicon.ico',
      meta: {
        viewport: 'idth=device-width, initial-scale=1, shrink-to-fit=no',
      },
      base: {
        href: 'http://localhost:8888',
        target: '_blank',
      },
      minify: false,
      cache: true,
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuilderPatterns: ['**/*', '!static-files*'],
    }),
  ],
};
